<style>
.files > li {
    float: left;
    width: 150px;
    border: 1px solid #eee;
    margin-bottom: 10px;
    margin-right: 10px;
    position: relative;
}

.files > li > .file-select {
    position: absolute;
    top: -4px;
    left: -1px;
}

.file-icon {
    text-align: center;
    font-size: 65px;
    color: #666;
    display: block;
    height: 100px;
}

.file-info {
    text-align: center;
    padding: 10px;
    background: #f4f4f4;
}

.file-name {
    font-weight: bold;
    color: #666;
    display: block;
    overflow: hidden !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.file-size {
    color: #999;
    font-size: 12px;
    display: block;
}

.files {
    list-style: none;
    margin: 0;
    padding: 0;
}

.file-icon.has-img {
    padding: 0;
}

.file-icon.has-img > img {
    max-width: 100%;
    height: auto;
    max-height: 92px;
}

</style>

<script data-exec-on-popstate>

$(function () {
    $('.file-delete').click(function () {

        var path = $(this).data('path');

        swal({
            title: "{{ trans('admin.delete_confirm') }}",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{{ trans('admin.confirm') }}",
            showLoaderOnConfirm: true,
            closeOnConfirm: false,
            cancelButtonText: "{{ trans('admin.cancel') }}",
            preConfirm: function () {
                alert("d")
                return new Promise(function (resolve) {

                    $.ajax({
                        method: 'delete',
                        url: '{{ $url['delete'] }}',
                        data: {
                            'files[]': [path],
                            _token: LA.token
                        },
                        success: function (data) {
                            $.pjax.reload('#pjax-container');

                            resolve(data);
                        }
                    });

                });
            }
        }).then(function (result) {
            var data = result.value;
            if (typeof data === 'object') {
                if (data.status) {
                    swal(data.message, '', 'success');
                } else {
                    swal(data.message, '', 'error');
                }
            }
        });
    });

    $('#moveModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var name = button.data('name');

        var modal = $(this);
        modal.find('[name=path]').val(name)
        modal.find('[name=new]').val(name)
    });

    $('#urlModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var url = button.data('url');

        $(this).find('input').val(url)
    });

    $('#file-move').on('submit', function (event) {

        event.preventDefault();

        var form = $(this);

        var path = form.find('[name=path]').val();
        var name = form.find('[name=new]').val();

        $.ajax({
            method: 'put',
            url: '{{ $url['move'] }}',
            data: {
                path: path,
                'new': name,
                _token: LA.token,
            },
            success: function (data) {
                $.pjax.reload('#pjax-container');

                if (typeof data === 'object') {
                    if (data.status) {
                        toastr.success(data.message);
                    } else {
                        toastr.error(data.message);
                    }
                }
            }
        });

        closeModal();
    });

    $('.file-upload').on('change', function () {
        $('.file-upload-form').submit();
    });

    $('#new-folder').on('submit', function (event) {

        event.preventDefault();

        var formData = new FormData(this);

        $.ajax({
            method: 'POST',
            url: '{{ $url['new-folder'] }}',
            data: formData,
            async: false,
            success: function (data) {
                $.pjax.reload('#pjax-container');

                if (typeof data === 'object') {
                    if (data.status) {
                        toastr.success(data.message);
                    } else {
                        toastr.error(data.message);
                    }
                }
            },
            cache: false,
            contentType: false,
            processData: false
        });

        closeModal();
    });

    function closeModal() {
        $("#moveModal").modal('toggle');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
    }

    $('.media-reload').click(function () {
        $.pjax.reload('#pjax-container');
    });

    $('.goto-url button').click(function () {
        var path = $('.goto-url input').val();
        $.pjax({container: '#pjax-container', url: '{{ $url['index'] }}?path=' + path});
    });

    $('.file-select>input').iCheck({checkboxClass: 'icheckbox_minimal-blue'});

    // 点击确认选择文件
    // $('#sure_select').click(function () {
    //     let files = $(".file-select input:checked").map(function () {
    //         return $(this).data("url");
    //     }).toArray();
    //
    //     if (!files.length) {
    //         return [];
    //     }
    //     return files;
    // });

    $('.file-delete-multiple').click(function () {
        var files = $(".file-select input:checked").map(function () {
            return $(this).val();
        }).toArray();

        if (!files.length) {
            return;
        }
        swal({
            title: "{{ trans('admin.delete_confirm') }}",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{{ trans('admin.confirm') }}",
            showLoaderOnConfirm: true,
            closeOnConfirm: false,
            cancelButtonText: "{{ trans('admin.cancel') }}",
            preConfirm: function () {
                return new Promise(function (resolve) {

                    $.ajax({
                        method: 'delete',
                        url: '{{ $url['delete'] }}',
                        data: {
                            'files[]': files,
                            _token: LA.token
                        },
                        success: function (data) {
                            $.pjax.reload('#pjax-container');

                            resolve(data);
                        }
                    });

                });
            }
        }).then(function (result) {
            var data = result.value;
            if (typeof data === 'object') {
                if (data.status) {
                    swal(data.message, '', 'success');
                } else {
                    swal(data.message, '', 'error');
                }
            }
        });
    });
});

</script>

<div class="row" id="media-select">
<!-- /.col -->
<div class="col-md-12">
{{--已选择的图片--}}
<ul class="files clearfix">
<template v-if="selected_urls.length==0">
    <li style="height: 50px;border: none;"></li>
</template>
<template v-else>
<li v-for="url in selected_urls">
<span class="file-icon has-img">
    <img :src="url" alt="Attachment">
</span>

</li>
</template>
</ul>

{{--模态框--}}
<div class="modal in" id="moveModal" tabindex="-1" role="dialog" aria-labelledby="moveModalLabel">
<div class="modal-dialog" role="document" style='width: 50%'>
<div class="modal-content">
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
    </button>
    <h4 class="modal-title" id="moveModalLabel">选择文件</h4>
</div>
<div class="box box-primary">

<div class="box-body no-padding">

<div class="mailbox-controls with-border">
<div class="btn-group">
    <a type="button" class="btn btn-default btn file-delete-multiple" title="Delete">
        <i class="fa fa-trash-o"></i>
    </a>
</div>
<div class="input-group input-group-sm pull-right goto-url" style="width: 250px;">
</div>

</div>

<!-- /.mailbox-read-message -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<ol class="breadcrumb" style="margin-bottom: 10px;">

<li @click="to_dir('/', 2, true)"><a><i class="fa fa-th-large"></i> </a></li>

<li v-for="n in nav"><a @click="to_dir(n.url, 2, true)"> @{{ n.name }}</a></li>
</ol>
<ul class="files clearfix media-list">
<template v-if="medias.length==0">
    <li style="height: 200px;border: none;"></li>
</template>
<template v-else>
<li v-for="item in medias" class='media-item' @click="item_click($event, item.base_name, item.isDir)">
                            <span v-if="!item.isDir" class="file-select">
                                <input type="checkbox" class='item-checkbox' :data-url="item.url"/>
{{--                                <input type="checkbox" v-model="item.name"/>--}}
                            </span>
                            {{--                            @{{item.preview}}--}}
                            <div v-html="item.preview"></div>

                            <div class="file-info">
                            <a class="file-name" :title="item.name">
                                @{{ item.icon }} @{{ item.base_name }}
                            </a>
                            <span class="file-size">
                              @{{ item.size }}&nbsp;

                                <div class="btn-group btn-group-xs pull-right" style='display: none'>
                                    <button type="button" class="btn btn-default btn-xs dropdown-toggle"
                                            data-toggle="dropdown">
                                        <span class="caret"></span>
                                        <span class="sr-only">Toggle Dropdown</span>
                                    </button>
                                    <ul class="dropdown-menu" role="menu">
                                        <li><a href="#" class="file-rename" data-toggle="modal" data-target="#moveModal"
                                               :data-name="item.name">Rename & Move</a></li>
                                        <li><a href="#" class="file-delete" :data-path="item.name">Delete</a></li>
                                        <li class="divider"></li>
                                        <li><a href="#" data-toggle="modal" data-target="#urlModal"
                                               :data-url="item.url">Url</a></li>
                                    </ul>
                                </div>
                            </span>
                            </div>
</li>
</template>
</ul>
<input type='button' id='sure_select' @click='sure_select()' value='确定' style='float: right;'
       class='btn btn-primary'></input>
</div>
</div>
</div>
</div>
</div>
{{--模态框--}}
</div>

</div>


<script src="{{ asset('statics/js/home/vue.min.js')}}"></script>
<script src="{{ asset('statics/js/home/axios.min.js')}}"></script>
<script>
$(function () {
    $("#grid-modal-16-loss_number_unit").css('left', $(".main-sidebar").width());
})
//回复
axios.interceptors.response.use((response) => {
    return response
}, (error) => {
    switch (error.response.status) {
        case 400:
            myalert(error.response.data.message)
            break
        //验证器验证不通过
        case 422:
            myalert(error.response.data.message)
            break
    }
    return Promise.reject(error)
})

let base_url = "{{$base_url}}"
let vm = new Vue({
    el: '#media-select',
    filters: {},
    components: {},
    data() {
        return {
            path: "/",
            medias: [],
            nav: [],
            selected_urls: [],
        };
    },
    created() {
        this.list()
    },
    methods: {
        list() {
            let _that = this

            $.ajax({
                method: 'get',
                url: '{{ $url['list'] }}',
                data: {
                    path: this.path,
                    // _token:LA.token
                },
                success: function (data) {
                    _that.medias = data.data.list
                    _that.nav = data.data.nav
                    console.log(data.data)
                    // $('.media-item').off('click')
                    // $(document).on('click', '.media-item', function () {
                    //     // @click="to_dir(item.base_name, 1, item.isDir)"
                    //     console.log("d")
                    //     if ($(this).data('isdir')) {//跳转目录,重新拉取列表
                    //         _that.to_dir($(this).data('base-name'), 1, true)
                    //     } else {//勾选图片
                    //         alert($(this).data('base-name'));
                    //     }
                    // })
                }
            });
        },
        item_click(event, base_name, is_dir) {
            if (is_dir) {//跳转目录,重新拉取列表
                this.to_dir(base_name, 1, true)
            } else {//勾选图片
                if (!$(event.target).hasClass('item-checkbox')) {
                    let _this_li = $(event.target).parents('.media-item')

                    let _this_checkbox = _this_li.find("input[type='checkbox']")
                    //.prop("tagName")
                    _this_checkbox.prop('checked', !_this_checkbox.prop('checked'))
                }
            }
        },
        to_dir(path, type = 1, is_dir) {//方式1追加路径 2重置路径为
            if (!is_dir) {
                return
            }
            if (type === 1) {
                this.path = this.path + path + '/'
            } else {
                this.path = path
            }
            this.medias = []
            this.list()
        },
        sure_select() {//确认选择文件
            let files = $(".file-select input:checked").map(function () {
                return $(this).data("url");
            }).toArray();

            if (!files.length) {
                this.selected_urls = [];
            } else {
                this.selected_urls = files;
            }
            //关闭模态框
            $("#moveModal").modal('toggle');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();
        }
    }
});

function myalert(msg, type = 'error') {
    //type  error或success
    sweetAlert(
        msg,
        '',
        type
    )
}

//获取表单数据
function getFormData() {
    var form_data = $('form').serializeArray()
    var data = {};
    $.each(form_data, function () {
        data[this.name] = this.value;
    });
    return data;
}
</script>
